<template>
    <van-popup
      v-model="showPopup"
      position="bottom"
      :style="{ height: '80%' }"
      round
      closeable
      @close="handleClose"
    >
      <div class="evaluation-form">
        <!-- 表单头部 -->
        <div class="form-header">
          <h3 class="form-title">服务评价</h3>
          <p class="form-subtitle">分享您的服务体验</p>
        </div>

        <!-- 订单信息 -->
        <div class="order-info" v-if="orderData">
          <div class="order-item">
            <span class="label">订单号：</span>
            <span class="value">{{ orderData.orderid }}</span>
          </div>
          <div class="order-item">
            <span class="label">服务类型：</span>
            <span class="value">{{ orderData.itemType }} - {{ getRepairTypes(orderData.repairTypes) }}</span>
          </div>
        </div>

        <!-- 评价表单 -->
        <van-form @submit="handleSubmit" class="evaluation-content">
          <!-- 评价标题 -->
          <van-field
            v-model="formData.title"
            name="title"
            label="评价标题"
            placeholder="请输入评价标题"
            :rules="[{ required: true, message: '请输入评价标题' }]"
            maxlength="50"
            show-word-limit
          />

          <!-- 评价内容 -->
          <van-field
            v-model="formData.content"
            name="content"
            label="评价内容"
            type="textarea"
            placeholder="请详细描述您的服务体验..."
            :rules="[{ required: true, message: '请输入评价内容' }]"
            rows="4"
            maxlength="500"
            show-word-limit
          />

          <!-- 服务评分 -->
          <div class="rating-section">
            <div class="rating-label">服务评分</div>
            <van-rate
              v-model="formData.rating"
              :size="24"
              color="#ff6b35"
              void-color="#eee"
              allow-half
            />
            <span class="rating-text">{{ getRatingText(formData.rating) }}</span>
          </div>

          <!-- 体验图片上传 -->
          <div class="upload-section">
            <div class="upload-label">体验图片</div>
            <van-uploader
              v-model="formData.images"
              multiple
              :max-count="3"
              :max-size="5 * 1024 * 1024"
              accept="image/*"
              upload-text="上传图片"
              @oversize="handleOversize"
              @delete="handleImageDelete"
            >
              <template #preview-cover="{ file }">
                <div class="preview-cover">
                  <van-icon name="eye-o" @click="previewImage(file)" />
                  <van-icon name="delete-o" @click="deleteImage(file)" />
                </div>
              </template>
            </van-uploader>
            <div class="upload-tip">最多上传3张图片，单张不超过5MB</div>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <van-button
              type="primary"
              native-type="submit"
              :loading="submitting"
              :disabled="!isFormValid"
              block
              round
              size="large"
            >
              {{ submitting ? '发布中...' : '发布评价' }}
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </template>

  <script setup>
  import { ref, computed, watch } from 'vue';
  import { publishReview, pushView, uploadImageApi } from '@/api/index.js';
  import { showToast, showSuccessToast, showFailToast, showImagePreview } from 'vant';
  import { useUserStore } from '@/stores/user.js';

  const userStore = useUserStore();

  // Props
  const props = defineProps({
    show: {
      type: Boolean,
      default: false
    },
    orderData: {
      type: Object,
      default: null
    }
  });

  // Emits
  const emit = defineEmits(['update:show', 'success']);

  // 响应式数据
  const showPopup = ref(false);
  const submitting = ref(false);

  // 表单数据
  const formData = ref({
    title: '',
    content: '',
    rating: 5,
    images: []
  });

  // 监听显示状态
  watch(() => props.show, (newVal) => {
    console.log('EvaluationForm 接收到 show prop 变化：', newVal);
    console.log('EvaluationForm 接收到 orderData：', props.orderData);
    showPopup.value = newVal;
    if (newVal) {
      resetForm();
    }
  });

  watch(showPopup, (newVal) => {
    console.log('EvaluationForm showPopup 状态变化：', newVal);
    emit('update:show', newVal);
  });

  // 计算属性
  const isFormValid = computed(() => {
    return formData.value.title.trim() &&
           formData.value.content.trim() &&
           formData.value.rating > 0;
  });

  // 解析维修类型
  const getRepairTypes = (repairTypes) => {
    if (!repairTypes) return '';
    try {
      const types = JSON.parse(repairTypes);
      return Array.isArray(types) ? types.join('、') : '';
    } catch (e) {
      return repairTypes;
    }
  };

  // 获取评分文本
  const getRatingText = (rating) => {
    if (rating >= 4.5) return '非常满意';
    if (rating >= 4) return '满意';
    if (rating >= 3) return '一般';
    if (rating >= 2) return '不满意';
    return '很不满意';
  };

  // 重置表单
  const resetForm = () => {
    formData.value = {
      title: '',
      content: '',
      rating: 5,
      images: []
    };
  };

  // 处理关闭
  const handleClose = () => {
    showPopup.value = false;
  };

  // 处理图片超大小
  const handleOversize = () => {
    showToast('图片大小不能超过5MB');
  };

  // 处理图片删除
  const handleImageDelete = (file, detail) => {
    console.log('删除图片:', file, detail);
  };

  // 预览图片
  const previewImage = (file) => {
    showImagePreview({
      images: [file.content || file.url],
      startPosition: 0,
      closeable: true
    });
  };

  // 删除图片
  const deleteImage = (file) => {
    const index = formData.value.images.findIndex(img => img === file);
    if (index > -1) {
      formData.value.images.splice(index, 1);
    }
  };

  // 上传图片到服务器
  const uploadImages = async (images) => {
    if (!images || images.length === 0) return null;

    try {
      const uploadPromises = images.map(async (image) => {
        // 如果是base64格式，需要转换为File对象
        let file;
        if (typeof image.content === 'string' && image.content.startsWith('data:image/')) {
          // 将base64转换为blob
          const response = await fetch(image.content);
          const blob = await response.blob();
          file = new File([blob], `evaluation-image-${Date.now()}.jpg`, { type: 'image/jpeg' });
        } else if (image.file instanceof File) {
          file = image.file;
        } else if (image.content instanceof File) {
          file = image.content;
        } else {
          console.warn('不支持的图片格式:', typeof image.content);
          return null;
        }

        // 创建FormData
        const formData = new FormData();
        formData.append('image', file);

        console.log('开始上传图片:', file.name, file.size);

        // 调用上传API
        const uploadResponse = await uploadImageApi(formData);
        console.log('图片上传结果:', uploadResponse);

        if (uploadResponse && uploadResponse.code === 200 && uploadResponse.data && uploadResponse.data.url) {
          console.log('图片上传成功，URL:', uploadResponse.data.url);
          return uploadResponse.data.url; // 返回图片URL
        } else {
          console.error('图片上传失败:', uploadResponse?.message);
          return null;
        }
      });

      const uploadedUrls = await Promise.all(uploadPromises);
      const validUrls = uploadedUrls.filter(url => url !== null);

      console.log('所有图片上传完成:', validUrls);
      return validUrls.length > 0 ? validUrls.join(',') : null;
    } catch (error) {
      console.error('图片上传异常:', error);
      return null;
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!props.orderData) {
      showFailToast('订单信息缺失');
      return;
    }

    try {
      submitting.value = true;

      // 先上传图片（如果有的话）
      let imageUrl = null;
      if (formData.value.images && formData.value.images.length > 0) {
        console.log('检测到图片，开始上传:', formData.value.images);

        imageUrl = await uploadImages(formData.value.images);
        if (formData.value.images.length > 0 && !imageUrl) {
          showFailToast('图片上传失败，请重试');
          return;
        }

        console.log('图片上传完成，URL:', imageUrl);
      }

      // 准备提交数据 - 只发送后端需要的字段
      const reviewData = {
        orderid: props.orderData.orderid,        // 关联订单id
        serviceid: props.orderData.serviceid,    // 关联服务id
        // 不需要传递userid，后端会从订单中自动获取
        score: formData.value.rating,            // 评分（1-5分）
        content: `${formData.value.title.trim()}: ${formData.value.content.trim()}`, // 评价内容（标题+内容）
        city: props.orderData.address ? props.orderData.address.split(' ')[0] : '未知城市', // 用户所在城市
        imageUrl: typeof imageUrl === 'string' ? imageUrl : null // 确保是字符串或null，不是对象
      };

      console.log('提交评价数据:', reviewData);
      console.log('图片URL详细信息:', {
        原始imageUrl: imageUrl,
        类型检查: typeof imageUrl,
        最终imageUrl: reviewData.imageUrl
      });

      // 调用API - 使用pushView方法发布到首页展示
      const response = await pushView(reviewData);
      console.log('评价提交结果:', response);

      if (response && response.code === 200) {
        showSuccessToast({
          message: '🌟 评价发布成功！感谢您的反馈',
          duration: 2500
        });

        // 关闭弹窗
        handleClose();

        // 通知父组件
        emit('success', reviewData);
      } else {
        const errorMsg = response?.message || '评价发布失败';
        showFailToast({
          message: errorMsg,
          duration: 2500
        });
      }
    } catch (error) {
      console.error('评价提交异常:', error);
      showFailToast({
        message: '网络异常，请稍后重试',
        duration: 2500
      });
    } finally {
      submitting.value = false;
    }
  };
  </script>

  <style lang="scss" scoped>
  .evaluation-form {
    padding: 20px;
    background: #fff;
    height: 100%;
    overflow-y: auto;
  }

  /* 表单头部 */
  .form-header {
    text-align: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
  }

  .form-title {
    font-size: 20px;
    font-weight: 700;
    color: #333;
    margin: 0 0 8px 0;
  }

  .form-subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
  }

  /* 订单信息 */
  .order-info {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 20px;
  }

  .order-item {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .label {
    color: #666;
    min-width: 80px;
    flex-shrink: 0;
  }

  .value {
    color: #333;
    flex: 1;
    font-weight: 500;
  }

  /* 评价内容 */
  .evaluation-content {
    .van-field {
      margin-bottom: 16px;
    }
  }

  /* 评分区域 */
  .rating-section {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;
  }

  .rating-label {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .rating-text {
    margin-left: 12px;
    font-size: 14px;
    color: #ff6b35;
    font-weight: 500;
  }

  /* 上传区域 */
  .upload-section {
    margin-bottom: 20px;
  }

  .upload-label {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
    text-align: center;
  }

  .preview-cover {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    background: rgba(0, 0, 0, 0.3);
    color: white;

    .van-icon {
      font-size: 20px;
      cursor: pointer;

      &:hover {
        color: #ff6b35;
      }
    }
  }

  /* 表单操作 */
  .form-actions {
    margin-top: 24px;
    padding-top: 20px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .evaluation-form {
      padding: 16px;
    }

    .form-title {
      font-size: 18px;
    }

    .rating-section {
      padding: 12px 0;
    }
  }
  </style>
